<template>
  <div class="system-dic-dialog-container">
    <CustomDialog
        :title="state.dialog.title"
        v-model:visible="state.dialog.isShowDialog"
        dialogWidth="900px"
        @close="closeDialog"
        @submit="onSubmitBtnIds"
        :showSubmit="true"
        :dialogFooterBtn="true"
    >
      <!--    <el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog" width="769px">-->
      <el-form ref="dictDialogFormRef" :rules="rules" :model="state.ruleForm" size="default" label-width="90px">
        <el-row :gutter="35">
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
            <el-form-item label="字典分类" prop="category">
              <el-autocomplete
                  v-model="state.ruleForm.category"
                  :fetch-suggestions="querySearch"
                  clearable
                  style="width: 100%"
                  placeholder="选择分类"
                  @select="handleSelect"
              >
                <template #default="{ item }">
                  <div class="value">{{ item.value }}</div>
                </template>
              </el-autocomplete>
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
            <el-form-item label="字典标题" prop="title">
              <el-input v-model="state.ruleForm.title" placeholder="请输入字典名称" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
            <el-form-item label="字段类型" prop="type">
              <el-input v-model="state.ruleForm.type" placeholder="请输入字典类型" clearable></el-input>
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
            <el-form-item label="字典状态" prop="status">
              <el-switch
                  v-model="state.ruleForm.status"
                  inline-prompt
                  active-text="启用"
                  inactive-text="禁用"
                  :active-value="1"
                  :inactive-value="0"
              ></el-switch>
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
            <el-form-item label="字典描述" prop="description">
              <el-input v-model="state.ruleForm.description" type="textarea" placeholder="请输入字典描述"
                        maxlength="150"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" size="default">取 消</el-button>
					<el-button type="primary" @click="onSubmit(dictDialogFormRef)" size="default">{{
              state.dialog.submitTxt
            }}</el-button>
				</span>
      </template>
      <!--    </el-dialog>-->
    </CustomDialog>
  </div>
</template>

<script setup lang="ts" name="systemDictDialog">
import {reactive, ref, nextTick} from 'vue';
import {dictApi} from '/@/api/sys/dict';
import type {FormInstance, FormRules} from 'element-plus';
import msg from '/@/utils/messageUtils';
import _ from 'lodash';
// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);

// 定义变量内容
const dictDialogFormRef = ref();

const state = reactive({
  categories: [] as Array<string>,
  options: [] as Array<string>,
  ruleForm: {
    id: '',
    title: '', // 字典名称
    type: '', // 字段名
    category: '', // 字典分类
    status: 1, // 字典状态
    description: '',
  },
  dialog: {
    isShowDialog: false,
    type: '',
    title: '',
    submitTxt: '',
  },
});

const handleSelect = (item: any) => {
  console.log('item: ', item);
};

const querySearch = (queryString: string, cb: any) => {
  const results = queryString ? state.categories.filter(createFilter(queryString)) : state.categories;
  console.log('autocomplete , results ', results);
  cb(results);
};

const createFilter = (queryString: string) => {
  return (restaurant: any) => {
    console.log('restaurant: ', restaurant, ' ,queryString: ', queryString);
    return restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0;
  };
};

const remoteMethod = (query: string) => {
  if (query) {
    const value = state.categories.filter((v: string) => {
      return v.toLowerCase().includes(query.toLowerCase());
    });
    if (_.isEmpty(value)) {
      state.options = [query];
    } else {
      state.options = value;
    }
    console.log('value: ', value);
  } else {
    state.options = [];
  }
};

const listCategory = () => {
  dictApi()
      .listCategory()
      .then((res) => {
        console.log('res: ', res);
        state.categories = res.data;
      })
      .catch((e) => {
      });
};

const rules = reactive<FormRules>({
  title: [{required: true, message: '请输入字典标题', trigger: 'blur'}],
  type: [{required: true, message: '请输入字典类型', trigger: 'blur'}],
  category: [{required: true, message: '请输入字典分类', trigger: 'blur'}],
});

// 打开弹窗
const openDialog = (type: string, row: RowDictype) => {
  listCategory();
  state.dialog.type = type;
  if (type === 'edit') {
    dictApi()
        .view(row.id)
        .then((res) => {
          const {data} = res;
          state.ruleForm = data;
          console.log('详情数据： ', data);
        })
        .catch((e) => {
        });
    state.ruleForm.id = state.dialog.title = '修改字典';
    state.dialog.submitTxt = '修 改';
  } else {
    state.dialog.title = '新增字典';
    state.dialog.submitTxt = '新 增';
    // 清空表单，此项需加表单验证才能使用
    nextTick(() => {
      console.log('重置字典内容');
      dictDialogFormRef.value.resetFields();
      dictDialogFormRef.value.clearValidate();
    });
  }
  state.dialog.isShowDialog = true;
};

// 关闭弹窗
const closeDialog = () => {
  state.dialog.isShowDialog = false;
};
// 取消
const onCancel = () => {
  closeDialog();
};
// 提交
const onSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid) => {
    if (valid) {
      try {
        if (state.dialog.type === 'add') {
          await dictApi().create(state.ruleForm);
        } else {
          await dictApi().update(state.ruleForm);
        }
        msg().success('操作成功');
        closeDialog();
        emit('refresh');
      } catch (error) {
        msg().error(error);
      }
    }
  });
};

// 暴露变量
defineExpose({
  openDialog,
});
</script>
